﻿using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using IdleTest.EFAndMVCDemo.IRepositories;
using IdleTest.EFAndMVCDemo.Models;
using IdleTest.EFAndMVCDemo.Repositories.Fakes;
using System.Data.Entity.Fakes;
using Microsoft.QualityTools.Testing.Fakes;
using System.Linq;
using IdleTest.EFAndMVCDemo.Repositories;

namespace IdleTest.EFAndMVCDemo.RepositoryTest
{
    [TestClass]
    public class UserRepositoryTest : BaseUserRepositoryTest
    {
        protected SqlFileContext dbContext;

        protected IDisposable TestContext;

        private IUserRepository userRepository
        {
            get { return new UserRepository(dbContext); }
        }

        protected override IRepository<UserModel, string> Repository
        {
            get { return userRepository; }
        }

        protected override IUserRepository UserRepository
        {
            get { return userRepository; }
        }

        [TestInitialize]
        public override void Init()
        {
            base.Init();

            if (dbContext == null)
            {
                TestContext = ShimsContext.Create(); //注意使用shim时必须先调用此方法（非全局可使用using）

                ShimSqlFileContext context = new ShimSqlFileContext();
                ShimDbSet<UserModel> shimDbSet = new ShimDbSet<UserModel>();

                shimDbSet.AddT0 = p =>
                {
                    if (this.ExistedUsers.Select(o => o.LoginName).Contains(p.LoginName)
                        || string.IsNullOrEmpty(p.LoginName))
                    {
                        throw new Exception();
                    }

                    this.ExistedUsers.Add(p);
                    return p;
                };

                shimDbSet.FindObjectArray = p =>
                {
                    if (p != null && p.Length > 0)
                    {
                        return this.ExistedUsers.FirstOrDefault(o => o.LoginName.Equals(p[0]));
                    }

                    return null;
                };

                context.UsersGet = () => shimDbSet;
                dbContext = context;
            }
        }

        [TestCleanup]
        public virtual void Dispose()
        {
            this.TestContext.Dispose();
        }

        [TestMethod]
        public override void InsertTest()
        {
            base.InsertTest();
        }

        [TestMethod]
        public override void GetSingleTest()
        {
            base.GetSingleTest();
        } 
    }
}
